import pyppeteer
from requests_html import HTMLSession
from requests.exceptions import RequestException, Timeout
import random
import time

USER_AGENTS = [
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 LBBROWSER",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; 360SE)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1",
    "Mozilla/5.0 (iPad; U; CPU OS 4_2_1 like Mac OS X; zh-cn) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5",
    "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre",
    "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:16.0) Gecko/20100101 Firefox/16.0",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
    "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10"
]
def fetch_url(url, timeout=10, max_retries=3, retry_delay=5):
    headers = {"User-Agent": random.choice(USER_AGENTS)}
    session = HTMLSession()
    try:
        response = session.get(url, headers=headers, timeout=timeout)
        # 在渲染之前设置编码
        response.html.render(timeout=timeout)
        # 在渲染之后，如果有必要，再次设置编码

        # 尝试使用不同的编码来解码响应内容
        content = None
        try:
            content = response.content.decode('gb18030')
        except UnicodeDecodeError:
            try:
                content = response.content.decode('utf-8')
            except UnicodeDecodeError:
                # 可以继续尝试其他编码，或者记录错误
                pass


        return response
    except (Timeout, pyppeteer.errors.TimeoutError):
        if max_retries > 0:
            print(f"Timeout occurred for {url}. Retrying in {retry_delay} seconds...")
            time.sleep(retry_delay)  # 指数退避
            return fetch_url(url, timeout, max_retries - 1, retry_delay * 2)
    except RequestException as e:
        print(f"Error fetching {url}: {e}")
    return None